using System.Collections.Generic;
using UnityEngine;

// 建筑预览类，用于在放置建筑前显示预览效果
public class BuildingPreview : MonoBehaviour
{
    // 预览状态枚举
    public enum BuildingPreviewState
    {
        POSITIVE,  // 可放置状态
        NEGATIVE   // 不可放置状态
    }

    [SerializeField] private Material positiveMaterial; // 可放置状态材质
    [SerializeField] private Material negativeMaterial; // 不可放置状态材质

    // 当前预览状态（默认NEGATIVE）
    public BuildingPreviewState State { get; private set; } = BuildingPreviewState.NEGATIVE;

    public BuildingData Data { get; private set; }       // 关联的建筑数据
    public BuildingModel BuildingModel { get; private set; } // 建筑模型实例

    private List<Renderer> renderers = new();  // 所有渲染器组件缓存
    private List<Collider> colliders = new();   // 所有碰撞体组件缓存

    // 初始化预览
    public void Setup(BuildingData data)
    {
        Data = data;
        // 实例化建筑模型
        BuildingModel = Instantiate(data.Model, transform.position, Quaternion.identity, transform);

        // 获取所有渲染器和碰撞体
        renderers.AddRange(BuildingModel.GetComponentsInChildren<Renderer>());
        colliders.AddRange(BuildingModel.GetComponentsInChildren<Collider>());

        // 禁用所有碰撞体（预览状态不需要物理碰撞）
        foreach (var col in colliders)
        {
            col.enabled = false;
        }

        SetPreviewMaterial(State); // 设置初始材质
    }

    // 设置预览材质
    private void SetPreviewMaterial(BuildingPreviewState newState)
    {
        // 根据状态选择材质
        Material previewMat = newState == BuildingPreviewState.POSITIVE ? positiveMaterial : negativeMaterial;

        // 更新所有渲染器材质
        foreach (var rend in renderers)
        {
            Material[] mats = new Material[rend.sharedMaterials.Length];
            for (int i = 0; i < mats.Length; i++)
                mats[i] = previewMat;
            rend.materials = mats;
        }
    }

    // 改变预览状态
    public void ChangeState(BuildingPreviewState newState)
    {
        if (newState == State) return;
        State = newState;
        SetPreviewMaterial(State);
    }

    // 旋转预览模型
    public void Rotate(int rotationStep)
    {
        BuildingModel.Rotate(rotationStep);
    }
}